<template>
  <div id="userManagement">
    <h2 style="font-size: 24px; font-weight: 700;"> 用户管理</h2>
    <!-- 列表展示 -->
     <!-- 正常情况下，微信小程序登录后 后端会生成用户的记录 但没有用户信息，小程序会引导用户完善个人信息， 当然需要 有至少一条用户的数据 用以区分用户 而且不需要我们手动添加用户 -->
    <!-- <a-button type="primary" @click="showModal">添加用户</a-button> -->
    <a-table :columns="columns" :data-source="dataSource" size="small" bordered>
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'birthday'">
          <div>
            <a-date-picker v-if="editableData[record.key]" v-model:value="editableData[record.key][column.dataIndex]"
              style="width: 100%" @change="(date) => handleDateChange(date, record.key)" />
            <template v-else>
              {{ dayjs(text).format('YYYY-MM-DD') }}
            </template>
          </div>
        </template>
        <template v-if="['name', 'realname', 'sex', 'address'].includes(column.dataIndex)">
          <div>
            <a-input v-if="editableData[record.key]" v-model:value="editableData[record.key][column.dataIndex]"
              style="margin: -5px 0" />

            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>

        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.key]">
              <a-flex :style="{ ...boxStyle }" justify="space-evenly" align="center">
                <a-typography-link @click="save(record.key)">保存修改</a-typography-link>
                <a-popconfirm title="确实要取消?" @confirm="cancel(record.key)" style="margin-left: 8px">
                  <a>取消编辑</a>
                </a-popconfirm>
              </a-flex>

            </span>
            <span v-else>
              <a @click="edit(record.key)">编辑用户信息</a>
            </span>
          </div>
        </template>
      </template>
    </a-table>

    <!-- 模态框组件 -->
    <a-modal v-model:open="open" title="编辑用户
  " @ok="handleOk">
      <!-- 表单组件 -->
      <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="Activity name">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="Instant delivery">
          <a-switch v-model:checked="formState.delivery" />
        </a-form-item>
        <a-form-item label="Activity type">
          <a-checkbox-group v-model:value="formState.type">
            <a-checkbox value="1" name="type">Online</a-checkbox>
            <a-checkbox value="2" name="type">Promotion</a-checkbox>
            <a-checkbox value="3" name="type">Offline</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="Resources">
          <a-radio-group v-model:value="formState.resource">
            <a-radio value="1">Sponsor</a-radio>
            <a-radio value="2">Venue</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="Activity form">
          <a-textarea v-model:value="formState.desc" />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">Create</a-button>
          <a-button style="margin-left: 10px">Cancel</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, toRaw, watch } from 'vue'
import { cloneDeep } from 'lodash-es';
import dayjs from 'dayjs';

const value1 = ref();
watch(value1, (newValue, oldValue) => {
  console.log(newValue, oldValue);
})
//编辑按钮 交互 flex布局
const boxStyle = {
  width: '100%',
  // height: '100%',
  borderRadius: '6px',
  // border: '1px solid #40a9ff',
};

// 计算年龄的工具函数
const calculateAge = (birthday) => {
  if (!birthday) return 0;
  const birthDate = dayjs(birthday);
  const currentDate = dayjs();
  return currentDate.diff(birthDate, 'year');
};

// 日期变化处理函数
const handleDateChange = (date, key) => {
  // 确保操作的是当前编辑行的数据
  if (editableData[key]) {
    // 更新年龄
    editableData[key].age = calculateAge(date);

    // 如果需要强制更新视图（仅在必要时使用）
    // dataSource.value = [...dataSource.value];
  }
};

// 表单
const formState = reactive({
  name: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
});
const onSubmit = () => {
  console.log('submit!', toRaw(formState));
};
const labelCol = {
  style: {
    width: '150px',
  },
};
const wrapperCol = {
  span: 14,
};

// 模态框
const open = ref(false);
const showModal = () => {
  open.value = true;
};
const handleOk = e => {
  console.log(e);
  open.value = false;
};

// 列表数据
const columns = [
  {
    title: '微信昵称',
    dataIndex: 'name',
    width: '15%',
  },
  {
    title: '真实姓名',
    dataIndex: 'realname',
    width: '15%',
  },
  {
    title: '年龄',
    dataIndex: 'age',
    width: '5%',
  },
  {
    title: '性别',
    dataIndex: 'sex',
    width: '15%',
  },
  {
    title: '出生日期',
    dataIndex: 'birthday',
    width: '20%',
  },
  {
    title: '地址',
    dataIndex: 'address',
    width: '15%',
  },
  {
    title: 'operation',
    dataIndex: 'operation',
  },

];

// 真实情况下， 数据应该从服务器获取
const data = [];
for (let i = 0; i < 10; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    realname: `London Park no. ${i}`,
    age: 32,
    sex: (i % 2 === 0 || i % 2 === -1) ? '男' : '女',
    birthday: '1991-05-01',
    address: `London Park no. ${i}`,
  });
}
const dataSource = ref(data);
const editableData = reactive({});
// 编辑操作
const edit = (key) => {
  const record = dataSource.value.find(item => item.key === key);
  editableData[key] = {
    ...record,
    birthday: dayjs(record.birthday, 'YYYY-MM-DD') // 转换日期
  };
};


// 保存操作
const save = (key) => {
  const editedData = editableData[key];
  editedData.birthday = editedData.birthday.format('YYYY-MM-DD'); // 转回字符串
  Object.assign(dataSource.value.find(item => item.key === key), editedData);
  delete editableData[key];
};
const cancel = key => {
  delete editableData[key];
};


</script>

<style scoped lang="less"></style>